package problem200;

//200.岛屿数量
//https://leetcode.cn/problems/number-of-islands/description/

class Solution {
    int n,m;
    boolean[][] st;
    int[] xx = {1,-1,0,0};
    int[] yy = {0,0,1,-1};
    public int numIslands(char[][] grid) {
        n = grid.length;
        m = grid[0].length;
        int ret = 0;
        st = new boolean[n][m];
        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                if(grid[i][j] == '1' && !st[i][j]) {
                    st[i][j] = true;
                    dfs(grid, i, j);
                    ret++;
                }
            }
        }
        return ret;
    }

    public void dfs(char[][] grid, int x, int y) {
        for(int i = 0; i<4; i++) {
            int dx = x + xx[i];
            int dy = y + yy[i];
            if(dx >= 0 && dx < n && dy >= 0 && dy < m && grid[dx][dy] == '1' && !st[dx][dy]) {
                st[dx][dy] = true;
                dfs(grid, dx, dy);
            }
        }
    }
}